package com.dawnClass.service.impl;

import com.dawnClass.mapper.*;
import com.dawnClass.pojo.*;
import com.dawnClass.service.MycourseService;
import com.dawnClass.util.ServiceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyCourseServiceImpl implements MycourseService {
    @Autowired
    private ConsumerCourseMapper consumerCourseMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private ChapterMapper chapterMapper;
    @Autowired
    private VideoMapper videoMapper;



    /**
     * 获取用户课程信息
     * @param consumerId
     * @return
     */
    @Override
    public ServiceResponse getById(Integer consumerId) {
//        获取用户课程数据
        ConsumerCourseExample consumerCourseExample = new ConsumerCourseExample();
        consumerCourseExample.setOrderByClause("learning_start_time desc");
        consumerCourseExample.createCriteria().andConsumerIdEqualTo(consumerId);
//        遍历得到的数据使用courseId查询课程详情
        List<Course> courseList = new ArrayList<>();
        List<ConsumerCourse> consumerCourseList = consumerCourseMapper.selectByExample(consumerCourseExample);
        for (ConsumerCourse consumerCourse : consumerCourseList){
            Course course = courseMapper.selectByPrimaryKey(consumerCourse.getCourseId());
//            将通过courseId查询到的课程信息封装到List中
            courseList.add(course);
        }
        return ServiceResponse.getSuccess(courseList);
    }

    /**
     * 判断当前登录用户是否购买了该课程
     * @param consumerId
     * @param videoId
     * @return
     */
    @Override
    public ServiceResponse ifBuyConsumer(Integer consumerId, Integer videoId) {
        Video video = videoMapper.selectByPrimaryKey(videoId);
        Chapter chapter = chapterMapper.selectByPrimaryKey(video.getChapterId());
        ConsumerCourseExample consumerCourseExample = new ConsumerCourseExample();
        consumerCourseExample.createCriteria()
                .andCourseIdEqualTo(chapter.getCourseId())
                .andConsumerIdEqualTo(consumerId);
        List<ConsumerCourse> consumerCourses = consumerCourseMapper.selectByExample(consumerCourseExample);
        if (consumerCourses.size() > 0){
            return ServiceResponse.getSuccess("用户已购买");
        }
        return ServiceResponse.getFail(chapter.getCourseId());
    }
}
